package com.yunkont.pigcontrol.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.yunkont.pigcontrol.R;
import com.yunkont.pigcontrol.activity.AllPigActivity;
import com.yunkont.pigcontrol.activity.SetTimeActivity;
import com.yunkont.pigcontrol.app.BaseApplicaiton;
import com.yunkont.pigcontrol.bean.ChartBena;
import com.yunkont.pigcontrol.bean.ChartEntity;
import com.yunkont.pigcontrol.bean.PigBean;
import com.yunkont.pigcontrol.net.UrlValue;
import com.yunkont.pigcontrol.view.BarChart;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.yunkont.pigcontrol.utils.Utils.getStatue;

/**
 * Created by ZJB on 2017/9/21.
 *
 * @ copyright: iwhere chengdu technology
 */

public class FirstFragment extends Fragment {

    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.tv_pigName)
    TextView tvPigName;
    @Bind(R.id.tv_chooseName)
    TextView tvChooseName;
    @Bind(R.id.tv_pigStaute)
    TextView tvPigStaute;
    @Bind(R.id.tv_net)
    TextView tvNet;
    @Bind(R.id.bc_barChart)
    BarChart bcBarChart;
    @Bind(R.id.tv_wx)
    TextView tvWx;
    @Bind(R.id.tv_ax)
    TextView tvAx;
    @Bind(R.id.tv_wy)
    TextView tvWy;
    @Bind(R.id.tv_ay)
    TextView tvAy;
    @Bind(R.id.tv_wz)
    TextView tvWz;
    @Bind(R.id.tv_aZ)
    TextView tvAZ;
    @Bind(R.id.tv_setTime)
    TextView tvSetTime;
    @Bind(R.id.tv_caiyangTime)
    TextView tvCaiyangTime;
    private boolean isNetComPelet = true;
    private PigBean.EmbeddedBean.PigDatasBean pigDatasBean;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_first, container, false);
        ButterKnife.bind(this, inflate);
        initView();
        return inflate;
    }

    private void initView() {
        initData();
    }


    //图表的数据
    private void initData() {
        addChartData(null);
        getChartData();
    }

    private void addChartData(final List<Float> charts){
        final List<ChartEntity> data = new ArrayList<>();
        final String[] strX = {"站(静止)","趴(静止)","躺(静止)","运动"};
        for(int i =0;i<4;i++){
            if(charts == null){
                data.add(new ChartEntity(strX[i], 0f));
            }else {
                data.add(new ChartEntity(strX[i], charts.get(i)));
            }
        }
        bcBarChart.setData(data);
        bcBarChart.setOnItemBarClickListener(new BarChart.OnItemBarClickListener() {
            @Override
            public void onClick(int position) {
                if(charts != null){
                    Toast.makeText(getActivity(),strX[position]+"："+charts.get(position)+"小时",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            mHandler.sendEmptyMessage(0);
            mHandler.sendEmptyMessage(1);
        } else {
            mHandler.removeMessages(0);
            mHandler.removeMessages(1);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (isNetComPelet) {
                        String currentPid = BaseApplicaiton.getInstance().getCurrentPid();
                        getPigById(currentPid);
                    }
                    mHandler.removeMessages(0);
                    mHandler.sendEmptyMessageDelayed(0, 5000);
                    break;
                case 1:
                    getChartData();
                    mHandler.sendEmptyMessageDelayed(1, 1000 *60 *10);
                    break;
            }
        }
    };

    /**
     * 获取图表数据
     */
    private void getChartData(){
        String currentPid = BaseApplicaiton.getInstance().getCurrentPid();
        OkHttpUtils.get()
                .url(UrlValue.chartCount)
                .addParams("pig",currentPid)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(getActivity(), "网络错误：" + e.toString(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ChartBena chartBena = JSON.parseObject(response, ChartBena.class);
                        addChartData(chartBena.getData());
                    }
                });
    }


    /**
     * 获取单个猪的信息
     *
     * @param pid
     */
    public void getPigById(String pid) {
        isNetComPelet = false;
        final long l = System.currentTimeMillis();
        OkHttpUtils.get()
                .addParams("size", 1 + "")
                .addParams("pigId", pid)
                .addParams("sort", "id,desc")
                .url(UrlValue.findByPigId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        isNetComPelet = true;
                        Toast.makeText(getActivity(), "网络错误：" + e.toString(), Toast.LENGTH_SHORT).show();
                        tvNet.setText("网络状态：网络错误 ");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        isNetComPelet = true;
                        long t = System.currentTimeMillis() - l;
                        Log.e("getPigById", "onResponse: " + response);
                        try {
                            PigBean pigBean = JSON.parseObject(response, PigBean.class);
                            pigDatasBean = pigBean.get_embedded().getPigDatas().get(0);
                            tvPigName.setText("当前猪：" + pigDatasBean.getPigId());
                            tvPigStaute.setText("当前姿态：" + getStatue(pigDatasBean.getPosture()));
                            tvNet.setText("网络状态：正常 " + t + " ms");
                            tvWx.setText("X角度：" + pigDatasBean.getWx());
                            tvWy.setText("Y角度：" + pigDatasBean.getWy());
                            tvWz.setText("Z角度：" + pigDatasBean.getWz());
                            tvAx.setText("X加速度：" + pigDatasBean.getAx());
                            tvAy.setText("Y加速度：" + pigDatasBean.getAy());
                            tvAZ.setText("Z加速度：" + pigDatasBean.getAz());
                            tvCaiyangTime.setText("采样时间间隔：" + pigDatasBean.getTime() + "分钟");
                            tvSetTime.setVisibility(View.VISIBLE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    @OnClick({R.id.tv_chooseName, R.id.tv_setTime})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_chooseName:
                startActivityForResult(new Intent(getActivity(), AllPigActivity.class), 80);
                break;
            case R.id.tv_setTime:
                Intent intent = new Intent(getActivity(), SetTimeActivity.class);
                intent.putExtra("url", BaseApplicaiton.getInstance().getLinkUrl());
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 80) {
            if (data != null) {
                String pigId = data.getStringExtra("pigId");
                String linkUrl = data.getStringExtra("linkUrl");
                if (!TextUtils.isEmpty(pigId)) {
                    tvPigName.setText("当前猪：" + pigId);
                    BaseApplicaiton.getInstance().setCurrentPid(pigId);
                    getPigById(pigId);
                }
                if(!TextUtils.isEmpty(linkUrl)){
                    BaseApplicaiton.getInstance().setLinkUrl(linkUrl);
                }
            }
        }
    }


}
